<?php
class cache{
	
	public function __construct(){
		global $app;
		$app->{"cache"} =& $this;
	}
	
	/**
	 * 建立Cache
	 * @param string $key
	 * @param mixed $data - 可輸入陣列、物件、字串
	 * @param int $time
	 */
	public function add($key, $data, $time = 3600){
		$cache_file = APP_PATH.CACHE_PATH."/{$key}";
		$cache = array(
			"time" => time() + $time,
			"content" => $data
		);
		$cache = serialize($cache);
		if(write_file($cache_file, $cache)){
			chmod($cache_file, 0770);
			return true;
		}else
			return false;
	}
	
	/**
	 * 取得Cache
	 * @param string $key
	 */
	public function get($key){
		$cache_file = APP_PATH.CACHE_PATH."/{$key}";
		if(! $cache = read_file($cache_file))
			return false;
		$cache = unserialize($cache);
		if($cache["time"] < time()){
			delete_file($cache_file);
			return false;
		}
		return $cache["content"];
	}
	
	/**
	 * 清空Cache資料夾
	 */
	public function clean(){
		return clean_dir(APP_PATH.CACHE_PATH);
	}
	
	/**
	 * 刪除Cache
	 * @param string $key
	 */
	public function delete($key){
		return delete_file(APP_PATH.CACHE_PATH."/{$key}");
	}
	
}
?>